import React, {useCallback, useEffect, useRef, useState} from 'react'
import {Image, Input, View} from '@tarojs/components'
import Taro, {useRouter} from '@tarojs/taro'
import Nav from '@/components/Nav/Nav'
import {getChatInfo, sendMessage} from '@/packageC/api/chat'
import {emojis} from '@/assets/constant/emojis'
import {useMaintain} from '@/hooks'
import {dealEmoji} from '@/uitls/uitl'
import './ChatRoom.scss'

export interface ChatListItem {
  content: string
  createTime: string
  direct: 'left' | 'right'
  id: string
  userInfo: {
    avatar: string
    id: string
    nickname: string
  }
}

const useEmojis = (scrollTo, setValue, setSendValue) => {
  const [selectFace, setSelectFace] = useState<boolean>(false)

  function onSelectFace () {
    setSelectFace(prevState => !prevState)
    scrollTo(300)
  }

  function onSelectEmoji (index: number) {
    setValue(prevState => prevState + emojis[index].emoji)
    setSendValue(prevState => prevState + emojis[index].test)
  }

  function onfocus () {
    setSelectFace(false)
  }

  return {
    selectFace, onSelectEmoji, onSelectFace, onfocus
  }
}

const useScroll = (chatList, getChatInfoList) => {
  let query = useRef<Taro.SelectorQuery>()
  const scrollTo = useCallback((duration) => {
    Taro.nextTick(() => {
      query.current?.select('.chat_list_wrap').boundingClientRect(rect => {
        Taro.pageScrollTo({
          scrollTop: rect.height,
          duration: duration,
          selector: '.chat_list_wrap',
          success: (res) => {
            console.log(res)
          }
        })
      }).exec()
    })
  }, [])
  useEffect(() => {
    let timer
    getChatInfoList()
    // let instance = Taro.getCurrentInstance()
    //
    // let observer = Taro.createIntersectionObserver(instance)
    // observer.observe()
    query.current = Taro.createSelectorQuery()

    timer = setInterval(() => {
      getChatInfoList()
    }, 3000)
    return () => {
      if (timer) {
        clearInterval(timer)
      }
    }
  }, [getChatInfoList])
  useEffect(() => {
    if (!chatList.length) return
    scrollTo(0)
  }, [scrollTo, chatList.length])
  return {
    scrollTo
  }
}

const ChatRoom: React.FC = () => {
  const {params} = useRouter<{ id: string, nickname: string }>()
  const [chatList, setChatList] = useState<ChatListItem[]>([])
  const [value, setValue] = useState('')
  const [sendValue, setSendValue] = useState('')

  function getChatInfoList () {
    getChatInfo(params.id).then((res: ChatListItem[]) => {
      if (chatList.length === res.length) {
        return
      }
      for (const chatListItem of res) {
        chatListItem.content = dealEmoji(chatListItem.content)
      }
      setChatList(res)
    })
  }

  const {scrollTo} = useScroll(chatList, getChatInfoList)

  const {selectFace, onSelectEmoji, onSelectFace, onfocus} = useEmojis(scrollTo, setValue, setSendValue)

  function onchange (e) {
    setValue(e.detail.value)
    setSendValue(e.detail.value)
  }

  async function onConfirm () {
    if (!sendValue) {
      await Taro.showToast({
        title: '发送内容不能为空',
        icon: 'none'
      })
      return
    }
    let id = sendMessage(params.id, sendValue)
    if (!id) {
      await Taro.showToast({
        title: '发送失败，请稍后重试',
        icon: 'none'
      })
      return
    }
    getChatInfoList()
    setValue('')
    setSendValue('')
  }

  const {onMaintain} = useMaintain()

  return <View className='container'>
    <View className='chat_room'>
      <Nav color='#000' background='#fff'>
        <View className='nickname'>{params.nickname}</View>
      </Nav>
    </View>
    <View className='chat_list_wrap' style={{paddingBottom: selectFace ? '200px' : ''}}>
      {
        chatList.map(chatListItem => <>
          {
            chatListItem.direct === 'left' ? <View className={`chat_list_item ${chatListItem.direct}`}>
              <Image className='chat_list_item_avatar' src={chatListItem.userInfo.avatar} />
              <View className='item_box'>
                <View className='item_box_nickname'>{chatListItem.userInfo.nickname || '空'}</View>
                <View className='item_box_content' dangerouslySetInnerHTML={{__html: chatListItem.content}} />
              </View>
            </View> : <View className={`chat_list_item ${chatListItem.direct}`}>
              <Image className='chat_list_item_avatar' src={chatListItem.userInfo.avatar} />
              <View className='item_box'>
                <View className='item_box_nickname'>{chatListItem.userInfo.nickname || '空'}</View>
                <View className='item_box_content' dangerouslySetInnerHTML={{__html: chatListItem.content}} />
              </View>
            </View>
          }
        </>)
      }
    </View>
    <View className={`sendInput_wrap ${selectFace ? 'select' : ''}`}>
      <View className='sendInput_input_wrap' style={{paddingBottom: selectFace ? '' : '17.5px'}}>
        <View className='iconfont ' onClick={onMaintain}>&#xe66c;</View>
        <View className='sendInput_wrap_input'>
          <Input placeholder='发消息...'
            cursorSpacing={20}
            confirmType='send'
            value={value}
            onInput={onchange}
            onConfirm={onConfirm}
            onFocus={onfocus}
          />
        </View>
        <View className={`iconfont face ${selectFace ? 'select' : ''}`} onClick={onSelectFace}>&#xe6d8;</View>
        <View className='iconfont' onClick={onMaintain}>&#xe62c;</View>
      </View>
      <View className={`emoji_wrap ${selectFace ? 'select' : ''}`}>
        {emojis.map((item, index) => <View key={index}
          className='emoji_wrap_item'
          hoverClass='emoji_hover'
          onClick={() => onSelectEmoji(index)}
        >{item.emoji}</View>)}
      </View>
    </View>
  </View>
}

export default ChatRoom
